package org.sunrise.game.center.client;

import org.sunrise.game.center.message.ReportMessage;
import org.sunrise.game.center.server.NodeManager;
import org.sunrise.game.common.log.LogCore;
import org.sunrise.game.common.message.MessageUtils;
import org.sunrise.game.common.network.message.ClientMessageManager;

public class ReportClientMessageManager extends ClientMessageManager {

    private long lastReportTime = 0;

    public ReportClientMessageManager(String nodeId) {
        super(nodeId);
    }

    @Override
    public void pulse() {
        try {
            pulseHandler();
            pulseReport();
            pulseSender();
        } catch (Exception e) {
            LogCore.ReportClient.error("DispatchThread pulse, error : ", e);
        }
    }

    @Override
    protected void pulseHandlerOne(Object data) {
        var message = MessageUtils.fromMessage((byte[]) data, ReportMessage.class);
        LogCore.ReportClient.debug("recv msg, cur NodeId = { {} }, from NodeId = { {} }, messageId = { {} }, data = { {} }", getNodeId(), message.getNodeId(), message.getMessageId(), message);
    }

    /**
     * 心跳上报
     */
    private void pulseReport() {
        long cur = System.currentTimeMillis();
        if (cur - lastReportTime >= NodeManager.INTERVAL) {
            lastReportTime = cur;
            NodeManager.report(getNodeId());
        }
    }
}
